import serial
from serial.serialutil import SerialTimeoutException


class Serial_port(serial.Serial):
    def __init__(self, port, baudrate, bytesize=8, stopbits=1, timeout=0.01, parity='N', **kwargs):
        """
        Args:
            port: 串口号
            baudrate: 波特率
            bytesize: 位
            stopbits:
            timeout: 延时
            parity:
            **kwargs:
        """
        super(Serial_port, self).__init__()
        self.port = port
        self.baudrate = baudrate
        self.bytesize = bytesize
        self.stopbits = stopbits
        self.timeout = timeout
        self.parity = parity
        """建立串口连接"""
        """设置串口参数：串口号，波特率，数据长度，停止位,延迟时间，校验位"""
        self.com = self.com_connect()

    def com_connect(self):
        isconnect = False
        while isconnect is False:
            try:
                mpu_ser = serial.Serial(port=self.port,
                                        baudrate=self.baudrate,
                                        bytesize=self.bytesize,
                                        stopbits=self.stopbits,
                                        timeout=self.timeout,
                                        parity=self.parity)
                isconnect = mpu_ser.is_open
            except IOError:
                print("%sconnecting %s%s" % ('-' * 20, self.port, '-' * 20))
            if isconnect:
                print("%s%s mpu connection success%s\r\n" % ('-' * 20, self.port, '-' * 20))
                return mpu_ser

    def com_is_open(self):
        print(f"{self.port} open")
        return self.com.is_open

    def reconnect(self):
        print("正在重新连接串口：{}".format(self.port))
        self.com = self.com_connect()

    def com_close(self):
        """关闭串口"""
        print(f"{self.port} close")
        self.com.close()

    def send(self, send_data):
        """封装好的串口发送"""
        send_len = self.com.write(str(send_data).encode())
        return send_len

    def receive(self, read_len=0):
        """封装好的串口接收"""
        if read_len:
            data = self.com.read(read_len).decode('utf-8')
        else:
            data = self.com.read().decode('utf-8')
        return data


if __name__ == '__main__':
    a = Serial_port('COM1', baudrate=115200)

    while True:
        a.send('aaaa')
